let baseUrl = ''
let btnLock = false
const request = function (config = {}) {
    let {
        url = '',
        method = 'POST',
        data = {},
        timeout = 20000,
        loading = false
    } = config
    return new Promise((resolve, reject) => {
        let header = {}
        if (uni.getStorageSync('token')) {
            header.token = uni.getStorageSync('token')
        }
        if (loading) {
            uni.showLoading({
                title: '加载中...'
            })
        }
        console.log(import.meta.env.MODE)
        if (import.meta.env.MODE === 'development') {
            url = '/api' + url
        } else {
            url = baseUrl + '/' + url
        }
        uni.request({
            header: {
                ...header,
                r: Date.parse(new Date())
            },
            url,
            method,
            data,
            timeout,
            success: res => {
                const { code, data, msg } = res.data
                switch (code) {
                    case 0:
                        resolve(data)
                        break
                    case 401:
                        if (!btnLock) {
                            btnLock = true
                            uni.showToast({
                                title: '登录信息已过期',
                                icon: 'none'
                            })
                            uni.removeStorageSync('token')
                            uni.removeStorageSync('userInfo')
                            setTimeout(() => {
                                uni.reLaunch({
                                    url: '/pages/index/index'
                                })
                            }, 2000)
                        }
                        break
                    default:
                        uni.showToast({
                            icon: 'none',
                            title: msg
                        })
                        reject(res.data)
                }
            },
            fail: err => {
                reject(err)
            },
            complete: () => {
                if (loading) {
                    uni.hideLoading()
                }
            }
        })
    })
}
export default request
